<?php if (!defined("MAIN_DIR")) { header("Location: /"); die; }

/*
 * -------------------------------------------------------
 * MySQL - class for working with MySQL DB
 * -------------------------------------------------------
 */
class MySQL {
	
	private $_connect = false;
	
	function __construct($server,$user,$password,$dbname,$locale="utf8"){
		$this->_connect = mysql_connect($server,$user,$password) or die("Can't connect to db. Invalid server/user/password.");
		mysql_select_db($dbname) or die("No access to db. Invalid db name.");
		mysql_query("set charset '$locale'");
		mysql_query("set character set '$locale'");
		mysql_query("set names '$locale'");
	}
	
	public function close(){
		mysql_close($this->_connect);
	}
	
	public function sendQuery($query){
		return mysql_query($query);
	}
	
	public function getQ($query){
		if ($result = mysql_query($query))
			return $result;
		else {
			$trace = debug_backtrace();
			$level = 0;
			if (in_array($trace[1]['function'], array('getCell', 'getRow', 'getColumn', 'getTable')))
				$level = 1;
			if (APP_STATUS == "debug"){
				$message = 
					'<p><strong>MySQL error</strong> in file <strong>'.$trace[$level]['file'].'</strong>'.
					" at line <strong>" .$trace[$level]['line']."</strong>
					(function <strong>" . $trace[$level]['function'] ."</strong>):<br/>"
					."\n<span style='color:blue'>".mysql_error()."</span>\n\n<pre>$query</pre></p>";
				die($message); 
			}
		}
	}
	
	public function getCell($query,$row_name=0){
		$cell = FALSE;
		if ($result = $this->getQ($query) AND $row = mysql_fetch_array($result))
			$cell = $row[$row_name];
		return $cell;
	}
	
	public function getRow($query){
		$row = array();
		if ($result = $this->getQ($query))
			$row = mysql_fetch_assoc($result);
		return $row;
	}
	
	public function getColumn($query, $makehash = FALSE){
		$data = array();
		$result = $this->getQ($query);
		if (!$makehash){
			while ($row = mysql_fetch_row($result))
				$data[] = $row[0];
		}
		else{
			while ($row = mysql_fetch_array($result))
				$data[$row{0}] = $row[$makehash];
		}
		return $data;
	}
	
	public function getTable($query, $keycol = NULL){
		$data = array();
		$result = $this->getQ($query);
		if (is_null($keycol)){
			while ($row = mysql_fetch_assoc($result))
				$data[] = $row;
		}
		else{
			while ($row = mysql_fetch_assoc($result))
				$data[$row{$keycol}] = $row;
		}
		return $data;
	}
}
?>